import { NgModel } from '@angular/forms';

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { ValueAccessorBase } from './value-accessor';

import { AsyncValidatorArray, ValidatorArray, ValidationResult, message, validate } from './validate';

/**
 * 基础的用于实现NgModel和FormControl的类，使用方法请参考OrganizationSelectComponent
 */
export abstract class ElementBase<T> extends ValueAccessorBase<T> {
  protected abstract model: NgModel;

  constructor(private validators: ValidatorArray, private asyncValidators: AsyncValidatorArray) {
    super();
  }

  protected validate(): Observable<ValidationResult> {
    // console.log('validate');
    return validate(this.validators, this.asyncValidators)(this.model.control);
  }

  protected get invalid(): Observable<boolean> {
    // console.log('validate');
    return this.validate().pipe(map(v => Object.keys(v || {}).length > 0));
  }

  protected get failures(): Observable<Array<string>> {
    return this.validate().pipe(map(v => Object.keys(v).map(k => message(v, k))));
  }
}
